package com.kinghood.infrastructure.config;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: RestTemplate配置类
 * @CreateDate: 2023/11/9 11:57
 * @Copyright版权所有 深圳金雅福控股集团有限公司
 * @Author: mjt
 * @Version: 1.0
 */
@Configuration
public class RestTemplateConfig {
    @Value("${ribbon.ReadTimeout:3000}")
    private int ribbonReadTimeout;
    @Value("${ribbon.ConnectTimeout:3000}")
    private int ribbonConnectionTimeout;


    /**
     * @description: 请求内部微服务的restTemplate
     * @date: 2023/11/9 11:12
     * @author: Tom
     * @param: []
     * @return: org.springframework.web.client.RestTemplate
     */
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        // ribbon超时时间配置
        httpRequestFactory.setReadTimeout(ribbonReadTimeout);
        httpRequestFactory.setConnectTimeout(ribbonConnectionTimeout);

        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            @SneakyThrows
            public void handleError(ClientHttpResponse response) {
                if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) {
                    super.handleError(response);
                }
            }
        });

        return restTemplate;
    }
}